package com.fulihui.information.core.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fulihui.information.core.db.ContentListItemDB;
import com.fulihui.information.dto.ContentListItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

import static org.springframework.util.CollectionUtils.isEmpty;

/**
 * 简单的类目资讯列表内容处理，按时间降序的列表
 *
 * @author Willard.Hu on 2016/12/27 0027.
 */
@Component("redisContentListItemDB")
public class RedisContentListItemDB implements ContentListItemDB {
    @Autowired
    protected JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    /**
     * 资讯内容存 Redis 的 Key
     */
    private static final String CONTENT_ITEM_JSON_KEY = "INFORMATION:CONTENT_ITEM_JSON";

    @Override
    public long save(ContentListItemDTO item) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hset(CONTENT_ITEM_JSON_KEY, item.getId(), JSON.toJSONString(item));
        }
    }

    @Override
    public long batchSave(Collection<ContentListItemDTO> items) {
        if (isEmpty(items)) {
            return -1;
        }
        Map<String, String> hash = new HashMap<>();
        items.forEach(it -> hash.put(it.getId(), JSON.toJSONString(it)));
        try (Jedis jedis = jedisPool.getResource()) {
            String res = jedis.hmset(CONTENT_ITEM_JSON_KEY, hash);
            return "OK".equals(res) ? items.size() : -1;
        }
    }

    @Override
    public boolean exists(String id) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hexists(CONTENT_ITEM_JSON_KEY, id);
        }
    }

    @Override
    public long batchDelete(String... ids) {
        if (ids == null || ids.length == 0) {
            return -1;
        }
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hdel(CONTENT_ITEM_JSON_KEY, ids);
        }
    }

    @Override
    public List<ContentListItemDTO> queryList(Collection<String> ids) {
        List<String> values = null;
        if (!isEmpty(ids)) {
            try (Jedis jedis = jedisPool.getResource()) {
                values = jedis.hmget(CONTENT_ITEM_JSON_KEY, ids.toArray(new String[ids.size()]));
            }
        }
        if (isEmpty(values)) {
            return new LinkedList<>(); // 空链表，用于处理置顶数据
        }

        // 上层业务会判断是否有置顶，有的话插入到第一个，所以用链表模型
        List<ContentListItemDTO> list = new LinkedList<>();
        for (String value : values) {
            ContentListItemDTO item = JSONObject.parseObject(value, ContentListItemDTO.class);
            if (item != null) {
                list.add(item);
            }
        }
        return list;
    }
}
